#!/bin/bash

type -p "pigz" && GZIP=pigz || GZIP=gzip
# TMPDIR=/tmp/hf-prof
# TMPDIR=`pwd`

set -x
# rm -rf $TMPDIR
# mkdir $TMPDIR

SLEEP_TIME=0

# EXE_PID=${EXE_PID:-$(pgrep -o "$1")}

# if [[ -z $EXE_PID ]] ; then
#     echo "Error getting EXE PID"
#     exit 1
# fi

perf record -BN --no-buffering -ag -e instructions:u -o $1.perf.data ./$1 &
# -- sleep ${SLEEP_TIME:-200}
sleep 1

EXE_PID=${EXE_PID:-$(pgrep -o "$1")}

for perf_pid in $(jobs -p)
do
    echo $perf_pid
    wait $perf_pid
done

if [[ -z $EXE_PID ]] ; then
    echo "Error getting EXE PID"
    exit 1
fi

perf script -i $1.perf.data --fields comm,pid,ip | sed -ne "/^[^   ]\+[   ]*$EXE_PID[   ]*\$/,+2p" | $GZIP -c > $1.perf.pds.gz

nm -S $1 > $1.nm

# pushd $TMPDIR/..

# TARFILE=${TMPDIR}.tgz

# tar cvzf $TARFILE `basename $TMPDIR`

# popd

# echo "Generated file $TARFILE"
